package be.niob.apps.huisarts.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import be.niob.apps.huisarts.helper.Http;
import be.niob.apps.huisarts.model.Wachtdienst;

public class WachtdienstService {

	public static final String TAG = WachtdienstService.class.getName();

	public static final String wachtlijstUrl = "http://www.huisarts.be/lijsten/wachtlijst.php?lang=nl";

	public static Wachtdienst getWachtdienstInGemeente(String gemeente,
			String postcode) throws ClientProtocolException, IOException {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("gemeente", gemeente));
		params.add(new BasicNameValuePair("postnummer", postcode));

		String html = Http.post(wachtlijstUrl, params);

		Document doc = Jsoup.parse(html);

		// selector here
		// Elements links = doc.select("a[href]");

		Elements trs = doc.select("body table table tr td:eq(1)");

		Wachtdienst wachtdienst = new Wachtdienst();

		wachtdienst.setGemeente(trs.get(0).text());
		wachtdienst.setPostcode(trs.get(1).text());
		wachtdienst.setNummer(trs.get(2).text());

		/*
		 * for (int i=0; i<trs.size()-1; i++) {
		 * 
		 * }
		 * 
		 * for (Element tr : trs) { Log.d(TAG, tr.html()); }
		 */

		return wachtdienst;
	}

	public static Map<String, String> getGemeenteKeuzes(String gemeente,
			String postcode) throws ClientProtocolException, IOException {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("gemeente", gemeente));
		params.add(new BasicNameValuePair("postnummer", postcode));

		String html = Http.post(wachtlijstUrl, params);
		Document doc = Jsoup.parse(html);

		Elements options = doc.select("select[name=nr] option");

		HashMap<String, String> gemeentes = new HashMap<String, String>();
		
		for (Element option : options) {
			gemeentes.put(option.val(), option.text());
		}
		
		return gemeentes;
	}

}
